package com.mazaiting.auth.security.extension.mobile;

import com.mazaiting.auth.constant.SecurityConst;
import com.mazaiting.auth.security.core.userdetails.user.SysUserDetailsServiceImpl;
import com.mazaiting.auth.utils.VerifyCodeUtil;
import com.mazaiting.redis.service.IRedisStringService;
import lombok.Data;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * 短信验证码认证授权提供者
 */
@Data
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    private IRedisStringService redisStringService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication;
        // 获取手机号
        String mobile = (String) authenticationToken.getPrincipal();
        // 获取验证码
        String code = (String) authenticationToken.getCredentials();
        // 验证验证码
        VerifyCodeUtil.check(redisStringService, SecurityConst.SMS_CODE_PREFIX + mobile, code);
        // 生成用户信息
        UserDetails userDetails = ((SysUserDetailsServiceImpl) userDetailsService).loadUserByMobile(mobile);
        // 需要设置权限 userDetails.getAuthorities()
        SmsCodeAuthenticationToken result = new SmsCodeAuthenticationToken(userDetails, authentication.getCredentials(), userDetails.getAuthorities());
        result.setDetails(authentication.getDetails());
        return result;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
